package xyz.renyumeng.xkm.es.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import xyz.renyumeng.xkm.es.repository.EsProductRepository;
import xyz.renyumeng.xkm.es.service.EsShopService;
import xyz.renyumeng.xkm.model.es.EsProduct;

import javax.annotation.Resource;

import static xyz.renyumeng.xkm.rabbitMQ.RabbitMqConstant.*;
import static xyz.renyumeng.xkm.redis.RedisConstants.LOCK_SHOP_KEY;

/**
 * @author renyumeng
 * @date Created in 11:21 2023/7/4
 */

@Slf4j
@Component
public class esServiceListener {

    @Resource
    private EsShopService esShopService;
    @Resource
    private EsProductRepository esProductRepository;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(name = ES_PRODUCT_EXCHANGE),
                    value = @Queue(ES_PRODUCT_QUEUE),
                    key = {ES_PRODUCT_INSERT_KEY, ES_PRODUCT_UPDATE_KEY}
            )
    )
    public void saveListener(EsProduct esProduct) {
        log.info("写入product,product={}", esProduct);
//        AtomicReference<Boolean> isExist = new AtomicReference<>(false);
//        esProductRepository.findById(esProduct.getId()).ifPresent(existEsProduct -> {
//            log.info("该product在文档中已经存在!");
//            isExist.set(true);
//        });
//        if (BooleanUtil.isFalse(isExist.get())) {
        esShopService.save(esProduct);
//        stringRedisTemplate.delete(LOCK_SHOP_KEY);

//        }
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(name = ES_PRODUCT_EXCHANGE),
                    value = @Queue(ES_PRODUCT_DELETE_QUEUE),
                    key = ES_PRODUCT_DELETE_KEY
            )
    )
    public void deleteListener(Long productId) {
        log.info("删除product,productId={}", productId);
        esProductRepository.deleteById(productId);
    }
}
